package root.electronclass.electronclass.other;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

import root.electronclass.electronclass.common.event.WebSocketEvent;
import root.electronclass.electronclass.mvp.rest.RestManager;

import org.greenrobot.eventbus.EventBus;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;

public class WebSocketService extends Service {
    private final static String TAG = "WebSocketService";
    public JWebSocketClient client;
    private JWebSocketClientBinder mBinder = new JWebSocketClientBinder();
    private static final long CLOSE_RECON_TIME = 15000;//连接断开或者连接错误立即重连

    private boolean isClose = false;
    //用于Activity和service通讯
    public class JWebSocketClientBinder extends Binder {
        public WebSocketService getService() {
            return WebSocketService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //初始化WebSocket
        if (intent == null){
            return START_STICKY;
        }
        isClose = false;
        initSocketClient();
        mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);//开启心跳检测
        return START_STICKY;
    }

    //这里是处理webscoket
    private void initSocketClient() {
        String url = "ws://api.dzbp.ztengit.com/api/pub/webSocket/"+ RestManager.getInstance().getTOKEN();
        //（如果加密，则为wss），服务器网址就是 URL。
        URI uri = URI.create(url);
        client = new JWebSocketClient(uri) {
            @Override
            public void onMessage(String message) {
                //message就是接收到的消息
                Log.d(TAG, "WebSocketService收到的消息：" + message);
                //这里我通过EvenBus获取接收的消息并更新ui
                EventBus.getDefault().post(new WebSocketEvent(message));
            }

            @Override
            public void onOpen(ServerHandshake handShakeData) {//在webSocket连接开启时调用
                Log.d(TAG, "WebSocket 连接成功   gunId:");
            }

            @Override
            public void onClose(int code, String reason, boolean remote) {//在连接断开时调用
                Log.d(TAG, "onClose() 连接断开_reason：" + reason);
                mHandler.removeCallbacks(heartBeatRunnable);
                mHandler.postDelayed(heartBeatRunnable, CLOSE_RECON_TIME);//开启心跳检测
            }

            @Override
            public void onError(Exception ex) {//在连接出错时调用
                Log.d(TAG, "onError() 连接出错：" + ex.getMessage());
                mHandler.removeCallbacks(heartBeatRunnable);
                mHandler.postDelayed(heartBeatRunnable, CLOSE_RECON_TIME);//开启心跳检测
            }
        };
        connect();
    }

    /**
     * 连接WebSocket
     */
    private void connect() {
        new Thread() {
            @Override
            public void run() {
                try {
                    //connectBlocking多出一个等待操作，会先连接再发送，否则未连接发送会报错
                    client.connectBlocking();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }




    @Override
    public boolean onUnbind(Intent intent) {

        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        closeConnect();
        super.onDestroy();
    }

    /**
     * 断开连接
     */
    public void closeConnect() {
        mHandler.removeCallbacks(heartBeatRunnable);
        try {
            if (null != client) {
                client.close();
                Log.v("WebSocketService", "断开链接");
                isClose = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            client = null;
        }
    }

    //    -------------------------------------WebSocket心跳检测------------------------------------------------
    private static final long HEART_BEAT_RATE = 10 * 1000;

    //每隔10秒进行一次对长连接的心跳检测
    private Handler mHandler = new Handler();
    private Runnable heartBeatRunnable = new Runnable() {
        @Override
        public void run() {
            if (client != null) {
                if (client.isClosed()) {
                    reconnectWs();
                    Log.d(TAG, "心跳包检测WebSocket连接状态：已关闭");
                } else if (client.isOpen()) {
                    Log.d(TAG, "心跳包检测WebSocket连接状态：已连接");
                } else {
                    Log.d(TAG, "心跳包检测WebSocket连接状态：已断开");
                }
            } else {
                //如果client已为空，重新初始化连接
                if (!isClose) {
                    initSocketClient();
                    Log.d(TAG, "心跳包检测WebSocket连接状态：client已为空，重新初始化连接");
                }
            }
            //每隔一定的时间，对长连接进行一次心跳检测
            mHandler.postDelayed(this, HEART_BEAT_RATE);
        }
    };

    /**
     * 开启重连
     */
    private void reconnectWs() {
        mHandler.removeCallbacks(heartBeatRunnable);
        new Thread() {
            @Override
            public void run() {
                try {
                    Log.d(TAG, "开启重连");
                    client.reconnectBlocking();


                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

}